<template>
  <div class="cart-page">
    <el-table :data="cartItems" style="width: 100%">
      <el-table-column prop="foodName" label="商品" />
      <el-table-column label="单价">
        <template #default="{ row }">{{ row.foodPrice }}元</template>
      </el-table-column>
      <el-table-column prop="quantity" label="数量" />
      <el-table-column label="小计">
        <template #default="{ row }">{{ row.foodPrice * row.quantity }}元</template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="danger" size="small" @click="removeItem(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="desk-input">
      <el-input
        v-model="deskId"
        placeholder="请输入桌号"
        type="number"
		:min="0"
        style="width: 200px; margin-bottom: 20px;"
      />
    </div>

    <div class="cart-footer">
      <span>总价：{{ totalPrice }}元</span>
      <el-button type="success" @click="submitOrder">提交订单</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { get, post } from '../utils/axios'
import qs from 'qs'

const cartItems = ref([])
const deskId = ref('') // 桌号输入

const totalPrice = computed(() =>
  cartItems.value.reduce((sum, i) => sum + i.foodPrice * i.quantity, 0)
)

function loadCart() {
  cartItems.value = JSON.parse(localStorage.getItem('cart') || '[]')
}

function removeItem(item) {
  const cart = JSON.parse(localStorage.getItem('cart') || '[]')
  localStorage.setItem('cart', JSON.stringify(cart.filter(i => i.foodId !== item.foodId)))
  loadCart()
  ElMessage.success('已删除')
}

/* 检查桌号是否存在 */
async function checkDeskExists(deskId) {
  try {
    const res = await get('/desk/checkExists', { deskId })
    return res === 'exists'
  } catch (error) {
    ElMessage.error('桌号验证失败，请重试')
    return false
  }
}

/* ---------- 提交订单 ---------- */
async function submitOrder() {
  if (!cartItems.value.length) return ElMessage.warning('购物车为空')

  const employeeId = Number(localStorage.getItem('employeeId'))
  const storeId = Number(localStorage.getItem('storeId'))
  if (!employeeId || !storeId) return ElMessage.warning('请先登录')

  if (!deskId.value) return ElMessage.warning('请输入桌号')
  
  // 验证桌号是否存在
  const deskExists = await checkDeskExists(deskId.value)
  if (!deskExists) {
    return ElMessage.error('桌号不存在，请输入正确的桌号')
  }

  const userId = 0 // 默认为0
  const foodIds   = cartItems.value.map(i => i.foodId)
  const foodCount = cartItems.value.map(i => i.quantity)

  /* 1. 检查库存 & 菜品状态 */
  try {
    const res = await get('/food/checkAndReduceStock', 
      { foodId: foodIds, foodCount },
      { paramsSerializer: p => qs.stringify(p, { arrayFormat: 'repeat' }) }
    )
    if (res !== 'success') {
      return ElMessage.error(res) // 直接显示后端返回的提示信息（库存不足或已下架）
    }
  } catch {
    return ElMessage.error('库存检查失败，请重试')
  }

  /* 2. 创建订单主表 */
  const orderlistStatus = '已支付'
  const orderlistTotalprice = totalPrice.value

  const orderId = await post('/orderlist/addorderlist', null, {
    params: { userId, deskId: Number(deskId.value), orderlistStatus, employeeId, orderlistTotalprice, storeId }
  })

  if (!orderId || orderId === '0') return ElMessage.error('创建订单失败')

  /* 3. 写入订单明细 */
  for (const item of cartItems.value) {
    const ok = await post('/orderlistdetails/insertOne', null, {
      params: {
        orderlistId: orderId,
        foodName: item.foodName,
        foodCount: item.quantity,
        foodPrice: item.foodPrice,
        detailsAllprice: item.foodPrice * item.quantity
      }
    })
    if (ok !== 'success') return ElMessage.error('写入订单明细失败')
  }

  /* 4. 清空购物车并跳转 */
  localStorage.removeItem('cart')
  cartItems.value = []
  ElMessage.success('订单提交成功')
}


onMounted(loadCart)
</script>

<style scoped>
.cart-page {
  padding: 20px;
}
.desk-input {
  margin-top: 20px;
}
.cart-footer {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
